package com.asset.dispoal.company.service.commom;

import com.asset.dispoal.company.domain.db.entity.SysCompanyDo;
import com.asset.dispoal.company.domain.db.mapper.SysCompanyMapper;
import com.asset.dispoal.company.dto.CompanyRequest;
import com.asset.dispoal.company.dto.CompanyResponse;
import com.asset.dispoal.company.service.converter.CompanyConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import tech.mhuang.pacebox.core.ddd.BaseCommand;
import tech.mhuang.pacebox.core.util.CollectionUtil;
import tech.mhuang.pacebox.core.util.StringUtil;
import tech.mhuang.pacebox.springboot.protocol.Result;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author qr
 * @date 2022/1/25$
 */
@Component
public class FindTreeCommand implements BaseCommand<CompanyRequest, Result<List<CompanyResponse>>> {

    @Autowired
    SysCompanyMapper companyMapper;

    @Override
    public Result<List<CompanyResponse>> execute(CompanyRequest request) {
        final SysCompanyDo companyDo = CompanyConverter.INSTANCE.reqToDo(request);
        final List<SysCompanyDo> sysCompanyDos = companyMapper.queryAll(companyDo);
        final List<CompanyResponse> companyResponses = CompanyConverter.INSTANCE.doToRes(sysCompanyDos);
        if (CollectionUtil.isEmpty(companyResponses)) {
            return Result.ok();
        }
        final List<CompanyResponse> collect = companyResponses.stream().filter(item -> StringUtil.isBlank(item.getParentId())).collect(Collectors.toList());
        for (CompanyResponse companyResponse : collect) {
            recursion(companyResponses, companyResponse);
        }
        final List<CompanyResponse> collect1 = companyResponses.stream().filter(item -> StringUtil.isNotBlank(item.getParentId())).collect(Collectors.toList());
        companyResponses.removeAll(collect1);
        return Result.ok(companyResponses);
    }

    private void recursion(List<CompanyResponse> collect, CompanyResponse companyResponse) {
        for (CompanyResponse response : collect) {
            if (companyResponse.getId().equals(response.getParentId())) {
                companyResponse.getResponseList().add(response);
                recursion(collect, response);
            }
        }
    }

}